import { Component, OnInit } from '@angular/core';
import { HttpHeaders, HttpClient } from '@angular/common/http';
import { FormGroup, FormControl } from '@angular/forms';

@Component({
  selector: 'app-register',
  templateUrl: './register.component.html',
  styleUrls: ['./register.component.css']
})
export class RegisterComponent implements OnInit {

  type: number = 2
  name: string
  email: string
  profile: string
  facilities: string
  numOfYears: number
  username: string
  password: string
  repassword: string
  captcha: string
  headers = new HttpHeaders({ 'Content-Type': 'application/json' })
  constructor(private http: HttpClient) { }

  registerForm = new FormGroup({
    type: new FormControl('2'),
    name: new FormControl(''),
    email: new FormControl(''),
    profile: new FormControl(''),
    facilities: new FormControl(''),
    numOfYears: new FormControl(''),
    username: new FormControl(''),
    password: new FormControl(''),
    repassword: new FormControl(''),
    captcha: new FormControl('')
  });

  ngOnInit(): void {
  }

  onSubmit(): void {
    console.log('this.registerForm.value', this.registerForm.value)
    // debugger
    if (this.registerForm.value['password'] != this.registerForm.value['repassword']) {
      alert('Passwod and Re-Enter Password are not same')
      return
    }
    this.http.post<any>('/api/user/register',
      this.registerForm.value,
      { headers: this.headers, reportProgress: true })
      .subscribe((data: any) => {
        console.log(data)
        if (data.status == 'success') {
          setTimeout(() => {
            window.location.assign('/login')
          }, 1000);
        } else if (data.status == 'codefail') {
          alert('Captcha is wrong')
        }
      })
  }

  reset(): void {
    console.log('reset')
    this.registerForm.reset()
  }

  refresh(): void {
    console.log('refresh')
    let captcha_img = <HTMLInputElement>document.getElementById('captcha_img')
    captcha_img.src = "/api/kaptcha?" + Math.random();
  }

  typeOnChange(value: number): void{
    if(value == 3){
      this.type = 3
    }else{
      this.type = 2
    }
  }
}
